package com.woniuxy.bookmallmanagersrever.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.bookmallmanagersrever.entity.TBook;
import com.woniuxy.bookmallmanagersrever.entity.TUrlPermission;
import com.woniuxy.bookmallmanagersrever.service.BookService;
import com.woniuxy.bookmallmanagersrever.vo.BookVo;
import com.woniuxy.bookmallmanagersrever.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
public class BookController {

    @Autowired
    BookService bookService ;

    @Value("${uploadPath}")
    private String uploadPath ;

    @GetMapping("/book/list")
    public ResponseResult<PageInfo<BookVo>> list(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            String name){
        ResponseResult<PageInfo<BookVo>> result = new ResponseResult<>();
        try {
            PageInfo<BookVo> lists = bookService.findBookByPage(now,size,name);
            result.setCode(200);
            result.setMsg("查询成功!");
            result.setData(lists);
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("查询失败!");
        }
        return result ;
    }

    @PostMapping("/book/uploadImg")
    public ResponseResult<String> upload(@RequestParam("uploadImg") MultipartFile multipartFile) {
        ResponseResult<String> result = new ResponseResult<>();
        try {
            String filename = multipartFile.getOriginalFilename();
            //修改上传文件的名字
            String uuid = "bookmall" + UUID.randomUUID().toString().replace("-", "");
            //a.jpg
            filename = uuid + filename.substring(filename.lastIndexOf("."));
            //F:/woniu/imgs/ew3erwerfwfsdfsdfasdfsdfd.jpg
            File f = new File(uploadPath, filename);
            //文件上传
            multipartFile.transferTo(f);
            result.setCode(200);
            result.setMsg("上传成功!");
            result.setData(filename);
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("上传失败!");
        }
        return  result ;
    }

    @PostMapping("/book/add")
    public ResponseResult<Void> add(@RequestBody TBook book){
        ResponseResult<Void> result = new ResponseResult<>();
        try {
            bookService.add(book);
            result.setCode(200);
            result.setMsg("添加成功!");
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("添加失败!");
        }
        return result ;
    }
}
